'''
Created on 19 Feb 2012

@author: gav.aiken
'''

import logging
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from scrape import scrapeGames


class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
          <html>
            <head>
                <script type="text/javascript">
    
                  var _gaq = _gaq || [];
                  _gaq.push(['_setAccount', 'UA-29328978-1']);
                  _gaq.push(['_trackPageview']);
                
                  (function() {
                    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                  })();
                
                </script>
            </head>
            <body>
              <center>
              <h3>Enter EA, XBox Live or PSN Id to see last 20 games</h3>
                  <form action="/" method="post">
                    Id: <input type="text" name="id" value="AikenBac0n" />
                    <input type="submit" value="Show History">
                  </form>
              </center>
            </body>
          </html>""")    
    def post(self):
        input = cgi.escape(self.request.get('id'))
        games = scrapeGames(input)
        
        if len(games) > 0:
            rows = ''
            for game in games:
                game.put()
                rows += '<tr><td>%s</td><td>%s</td><td>(%s)</td><td>%d</td><td></td><td>%d</td><td>%s</td><td>(%s)</td></tr>\n' % \
                        ( game.result, game.playerId, game.playerTeam, game.playerScore, game.opponentScore, game.opponentId, game.opponentTeam )
            table = """<table border="0" c>
                    <tr>
                        <th>Result</th>
                        <th>Player</th>
                        <th>(PlayerTeam)</th>
                        <th>Scored</th>
                        <th></th>
                        <th>Conceded</th>
                        <th>Opponent</th>
                        <th>(OpponentTeam)</th>
                    </tr>
                    """ + rows + """
                  </table>"""
            error = ''
        else:
            table = ''
            error = '<b>Sorry - No records found for ' + input + ' - this can be a bad ID or if EA think we\'re pummeling them </b>'
            
        self.response.out.write("""
          <html>
            <head>
                <script type="text/javascript">
    
                  var _gaq = _gaq || [];
                  _gaq.push(['_setAccount', 'UA-29328978-1']);
                  _gaq.push(['_trackPageview']);
                
                  (function() {
                    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                  })();
                
                </script>
            </head>
            <body>
              <center>
                  <h3>Welcome """ + input + """</h3>
                  <form action="/" method="post">
                    Id: <input type="text" name="id" value=""" + input + """ />
                    <input type="submit" value="Show History" alt="Can take up to 1 minute">
                  </form>
                  """ + table + """
                  """ + error + """
              </center>
            </body>
          </html>""")

application = webapp.WSGIApplication([('/', MainPage)], debug=True)

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s')
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
